package com.kingwood.algorithm.test;

/**
 * @Author 22025812
 * @Description: 求字符串中所有整数的最小和
 * https://fcqian.blog.csdn.net/article/details/127418073
 * @Date: 2024/3/27 9:13
 * @Modified By：
 * @Version 1.0
 */
public class GetMinSum {

    public static long getMinSum(String str) {
        long sum = 0;
        int len = str.length();
        boolean isNegative = false;
        StringBuilder negativeStr = new StringBuilder();

        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (c >= '0' && c <= '9') {
                if (isNegative) {
                    negativeStr.append(c);
                    for (int j = i+1; j < len; j++) {
                        if (str.charAt(j) >= '0' && str.charAt(j) <= '9') {
                            negativeStr.append(str.charAt(j));
                            i = j;
                        } else {
                            negativeStr.append('#');
                            break;
                        }
                    }
                } else {
                    sum += (c - '0');
                }
            } else {
                isNegative = c == '-';
            }
        }

        if (negativeStr.length() > 0) {
            String[] numArr = negativeStr.toString().split("#");
            for (String num : numArr) {
                sum -= Integer.parseInt(num);
            }
        }

        return sum;
    }


    public static void main(String[] args) {
        String str = "bb1234aa";
        System.out.println(getMinSum(str));
        str = "bb12-34aa--10c5--90$+-21";
        System.out.println(getMinSum(str));
    }
}
